<route lang="jsonc" type="page">
{
  "style": {
    "navigationBarTitleText": "全球排行榜",
    "navigationBarBackgroundColor": "#fd79a8",
    "navigationBarTextStyle": "white"
  }
}
</route>

<template>
  <view class="ranking-page">
    <!-- 顶部统计卡片 -->
    <view class="header-stats">
      <view class="stat-card">
        <text class="stat-number">{{ formatNumber(globalStats?.totalUsers || 0) }}</text>
        <text class="stat-label">总玩家</text>
      </view>
      <view class="stat-card">
        <text class="stat-number">{{ formatNumber(globalStats?.totalEliminatedCount || 0) }}</text>
        <text class="stat-label">全球消灭</text>
      </view>
      <view class="stat-card">
        <text class="stat-number">{{ globalStats?.todayActiveUsers || 0 }}</text>
        <text class="stat-label">今日活跃</text>
      </view>
    </view>

    <!-- 标签页切换 -->
    <view class="tab-container">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'emoji' }"
        @click="switchTab('emoji')"
      >
        <text class="tab-text">Emoji 排行榜</text>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'global' }"
        @click="switchTab('global')"
      >
        <text class="tab-text">全球统计</text>
      </view>
    </view>

    <!-- Emoji排行榜内容 -->
    <view v-if="activeTab === 'emoji'" class="tab-content">
      <!-- 排行榜筛选 -->
      <view class="filter-container">
        <view class="filter-item">
          <text class="filter-label">显示数量:</text>
          <picker 
            :value="rankingLimitIndex" 
            :range="rankingLimitOptions"
            @change="onRankingLimitChange"
          >
            <view class="picker-text">{{ rankingLimitOptions[rankingLimitIndex] }}</view>
          </picker>
        </view>
      </view>

      <!-- Emoji排行榜列表 -->
      <view class="ranking-list">
        <view 
          class="ranking-item" 
          v-for="(item, index) in emojiRanking" 
          :key="item.emojiChar"
          :class="{ 
            'top-1': index === 0,
            'top-2': index === 1, 
            'top-3': index === 2 
          }"
        >
          <view class="rank-number">
            <text v-if="index < 3" class="medal">{{ ['🥇', '🥈', '🥉'][index] }}</text>
            <text v-else class="rank-text">{{ index + 1 }}</text>
          </view>
          <text class="emoji-char">{{ formatEmojiChar(item.emojiChar, item.emojiUnicode) }}</text>
          <view class="item-details">
            <text class="eliminated-count">{{ formatNumber(item.totalEliminatedCount) }}次</text>
            <text class="user-count">{{ item.userCount }}人消灭</text>
            <text class="percentage">{{ item.percentage.toFixed(1) }}%</text>
          </view>
          <view class="trend-indicator">
            <text class="avg-per-user">人均{{ item.avgPerUser.toFixed(1) }}次</text>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view v-if="emojiRanking.length > 0" class="load-more">
        <button 
          class="load-more-btn" 
          @click="loadMoreRanking"
          :disabled="loadingMore"
        >
          {{ loadingMore ? '加载中...' : '加载更多' }}
        </button>
      </view>
    </view>

    <!-- 全球统计内容 -->
    <view v-if="activeTab === 'global'" class="tab-content">
      <!-- 全球基本统计 -->
      <view class="stats-section">
        <text class="section-title">基本统计</text>
        <view class="stats-grid">
          <view class="stat-item">
            <text class="stat-value">{{ globalStats?.totalPlayCount || 0 }}</text>
            <text class="stat-label">总游戏局数</text>
          </view>
          <view class="stat-item">
            <text class="stat-value">{{ globalStats?.todayPlayCount || 0 }}</text>
            <text class="stat-label">今日游戏局数</text>
          </view>
          <view class="stat-item">
            <text class="stat-value">{{ globalStats?.globalBestScore || 0 }}</text>
            <text class="stat-label">全球最高分</text>
          </view>
          <view class="stat-item">
            <text class="stat-value">{{ globalStats?.globalAvgScore?.toFixed(0) || 0 }}</text>
            <text class="stat-label">平均分数</text>
          </view>
          <view class="stat-item">
            <text class="stat-value">{{ globalStats?.totalPlayTimeHours || 0 }}</text>
            <text class="stat-label">总游戏时长(小时)</text>
          </view>
          <view class="stat-item">
            <text class="stat-value">{{ formatNumber(globalStats?.todayEliminatedCount || 0) }}</text>
            <text class="stat-label">今日消灭总数</text>
          </view>
        </view>
      </view>

      <!-- 游戏结果分布 -->
      <view class="stats-section" v-if="globalStats?.resultDistribution">
        <text class="section-title">游戏结果分布</text>
        <view class="result-chart">
          <view class="result-item">
            <view class="result-bar">
              <view 
                class="result-fill completed" 
                :style="{ width: globalStats.resultDistribution.completionRate + '%' }"
              ></view>
            </view>
            <text class="result-label">
              完成游戏 {{ globalStats.resultDistribution.completedCount }}局 
              ({{ globalStats.resultDistribution.completionRate.toFixed(1) }}%)
            </text>
          </view>
          <view class="result-item">
            <view class="result-bar">
              <view 
                class="result-fill timeout" 
                :style="{ 
                  width: ((globalStats.resultDistribution.timeoutCount / globalStats.totalPlayCount) * 100) + '%' 
                }"
              ></view>
            </view>
            <text class="result-label">
              超时结束 {{ globalStats.resultDistribution.timeoutCount }}局
            </text>
          </view>
          <view class="result-item">
            <view class="result-bar">
              <view 
                class="result-fill quit" 
                :style="{ 
                  width: ((globalStats.resultDistribution.quitCount / globalStats.totalPlayCount) * 100) + '%' 
                }"
              ></view>
            </view>
            <text class="result-label">
              提前退出 {{ globalStats.resultDistribution.quitCount }}局
            </text>
          </view>
        </view>
      </view>

      <!-- 分数段分布 -->
      <view class="stats-section" v-if="globalStats?.scoreDistributions">
        <text class="section-title">分数段分布</text>
        <view class="score-chart">
          <view 
            class="score-item" 
            v-for="dist in globalStats.scoreDistributions" 
            :key="dist.scoreRange"
          >
            <text class="score-range">{{ dist.scoreRange }}分</text>
            <view class="score-bar">
              <view 
                class="score-fill" 
                :style="{ width: dist.percentage + '%' }"
              ></view>
            </view>
            <text class="score-count">{{ dist.playCount }}局 ({{ dist.percentage.toFixed(1) }}%)</text>
          </view>
        </view>
      </view>

      <!-- 热门Emoji Top 5 -->
      <view class="stats-section" v-if="globalStats?.popularEmojis">
        <text class="section-title">最受欢迎 Emoji</text>
        <view class="popular-emoji-list">
          <view 
            class="popular-emoji-item" 
            v-for="(emoji, index) in globalStats.popularEmojis" 
            :key="emoji.emojiChar"
          >
            <text class="emoji-rank">{{ index + 1 }}</text>
            <text class="emoji-char">{{ formatEmojiChar(emoji.emojiChar, emoji.emojiUnicode) }}</text>
            <view class="emoji-stats">
              <text class="emoji-count">{{ formatNumber(emoji.eliminatedCount) }}次</text>
              <text class="emoji-users">{{ emoji.userCount }}人</text>
            </view>
            <text class="emoji-percentage">{{ emoji.percentage.toFixed(1) }}%</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作按钮 -->
    <view class="bottom-actions">
      <button class="action-btn" @click="refreshData">刷新数据</button>
      <button class="action-btn" @click="backToGame">返回游戏</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { httpGet } from '@/http/http'

defineOptions({
  name: 'EmojiRanking'
})

// 当前活跃标签
const activeTab = ref('emoji')

// 全球统计数据
const globalStats = ref(null)

// Emoji排行榜数据
const emojiRanking = ref([])

// 排行榜数量选项
const rankingLimitOptions = ['20', '50', '100']
const rankingLimitIndex = ref(0)

// 加载状态
const loading = ref(true)
const loadingMore = ref(false)

// 页面挂载时加载数据
onMounted(async () => {
  await loadData()
})

// 加载所有数据
async function loadData() {
  try {
    loading.value = true
    await Promise.all([
      loadGlobalStats(),
      loadEmojiRanking()
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
    uni.showToast({
      title: '加载数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载全球统计数据
async function loadGlobalStats() {
  try {
    const response = await httpGet('/api/miniapp/game/stats/global/emoji_eliminate')
    if (response.code === 200) {
      globalStats.value = response.data
    }
  } catch (error) {
    console.error('加载全球统计失败:', error)
  }
}

// 加载Emoji排行榜
async function loadEmojiRanking() {
  try {
    const limit = parseInt(rankingLimitOptions[rankingLimitIndex.value])
    const response = await httpGet(`/api/miniapp/game/stats/emoji/ranking/emoji_eliminate?limit=${limit}`)
    if (response.code === 200) {
      emojiRanking.value = response.data || []
    }
  } catch (error) {
    console.error('加载Emoji排行榜失败:', error)
  }
}

// 切换标签
function switchTab(tab: string) {
  activeTab.value = tab
}

// 排行榜数量变化
function onRankingLimitChange(e: any) {
  rankingLimitIndex.value = e.detail.value
  loadEmojiRanking()
}

// 加载更多排行榜数据
async function loadMoreRanking() {
  if (loadingMore.value) return
  
  try {
    loadingMore.value = true
    const currentLimit = parseInt(rankingLimitOptions[rankingLimitIndex.value])
    const newLimit = currentLimit + 20
    
    const response = await httpGet(`/api/miniapp/game/stats/emoji/ranking/emoji_eliminate?limit=${newLimit}`)
    if (response.code === 200 && response.data) {
      emojiRanking.value = response.data
    }
  } catch (error) {
    console.error('加载更多数据失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loadingMore.value = false
  }
}

// 刷新数据
async function refreshData() {
  await loadData()
  uni.showToast({
    title: '数据已刷新',
    icon: 'success'
  })
}

// 返回游戏
function backToGame() {
  uni.navigateBack({
    delta: 2  // 返回到游戏页面（跳过统计页面）
  })
}

// 格式化数字显示
function formatNumber(num: number): string {
  if (num >= 100000000) {
    return `${(num / 100000000).toFixed(1)}亿`
  } else if (num >= 10000) {
    return `${(num / 10000).toFixed(1)}万`
  } else if (num >= 1000) {
    return `${(num / 1000).toFixed(1)}k`
  } else {
    return num.toString()
  }
}

// 格式化emoji字符显示
function formatEmojiChar(emojiChar: string, emojiUnicode: string): string {
  // 如果emojiChar存在且不是Unicode编码，直接返回
  if (emojiChar && !emojiChar.match(/^[0-9A-F]+$/i)) {
    return emojiChar
  }
  
  // 否则尝试从Unicode编码转换
  if (emojiUnicode) {
    try {
      const codePoint = parseInt(emojiUnicode, 16)
      return String.fromCodePoint(codePoint)
    } catch (e) {
      console.warn('无法解析emoji Unicode:', emojiUnicode)
      return emojiChar || '❓'
    }
  }
  
  return emojiChar || '❓'
}
</script>

<style lang="scss" scoped>
.ranking-page {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  min-height: 100vh;
  padding: 20rpx;
}

.header-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
  
  .stat-card {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 16rpx;
    padding: 24rpx;
    flex: 1;
    margin: 0 10rpx;
    text-align: center;
    
    .stat-number {
      display: block;
      font-size: 32rpx;
      font-weight: bold;
      color: #fd79a8;
      margin-bottom: 8rpx;
    }
    
    .stat-label {
      font-size: 24rpx;
      color: #666;
    }
  }
}

.tab-container {
  display: flex;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  
  .tab-item {
    flex: 1;
    padding: 24rpx;
    text-align: center;
    background: transparent;
    transition: all 0.3s ease;
    
    &.active {
      background: #fd79a8;
      
      .tab-text {
        color: white;
        font-weight: bold;
      }
    }
    
    .tab-text {
      font-size: 28rpx;
      color: #333;
    }
  }
}

.tab-content {
  .filter-container {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 16rpx;
    padding: 20rpx 30rpx;
    margin-bottom: 20rpx;
    
    .filter-item {
      display: flex;
      align-items: center;
      
      .filter-label {
        font-size: 28rpx;
        color: #333;
        margin-right: 20rpx;
      }
      
      .picker-text {
        font-size: 28rpx;
        color: #fd79a8;
        font-weight: bold;
      }
    }
  }
}

.ranking-list {
  .ranking-item {
    background: rgba(255, 255, 255, 0.9);
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 16rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
    
    &.top-1 {
      background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
      box-shadow: 0 8rpx 24rpx rgba(255, 215, 0, 0.3);
    }
    
    &.top-2 {
      background: linear-gradient(135deg, #c0c0c0 0%, #dcdcdc 100%);
      box-shadow: 0 8rpx 24rpx rgba(192, 192, 192, 0.3);
    }
    
    &.top-3 {
      background: linear-gradient(135deg, #cd7f32 0%, #daa520 100%);
      box-shadow: 0 8rpx 24rpx rgba(205, 127, 50, 0.3);
    }
    
    .rank-number {
      width: 80rpx;
      text-align: center;
      
      .medal {
        font-size: 40rpx;
      }
      
      .rank-text {
        font-size: 28rpx;
        font-weight: bold;
        color: #333;
      }
    }
    
    .emoji-char {
      font-size: 48rpx;
      margin: 0 20rpx;
    }
    
    .item-details {
      flex: 1;
      
      .eliminated-count {
        display: block;
        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 4rpx;
      }
      
      .user-count {
        display: block;
        font-size: 24rpx;
        color: #666;
        margin-bottom: 4rpx;
      }
      
      .percentage {
        display: block;
        font-size: 24rpx;
        color: #fd79a8;
        font-weight: bold;
      }
    }
    
    .trend-indicator {
      .avg-per-user {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}

.load-more {
  text-align: center;
  margin: 30rpx 0;
  
  .load-more-btn {
    background: rgba(255, 255, 255, 0.9);
    color: #fd79a8;
    border: 2rpx solid #fd79a8;
    border-radius: 25rpx;
    padding: 20rpx 40rpx;
    font-size: 28rpx;
    
    &:disabled {
      opacity: 0.6;
    }
  }
}

.stats-section {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
  
  .stat-item {
    text-align: center;
    padding: 20rpx;
    background: #f5f5f5;
    border-radius: 12rpx;
    
    .stat-value {
      display: block;
      font-size: 28rpx;
      font-weight: bold;
      color: #fd79a8;
      margin-bottom: 8rpx;
    }
    
    .stat-label {
      font-size: 22rpx;
      color: #666;
    }
  }
}

.result-chart, .score-chart {
  .result-item, .score-item {
    margin-bottom: 20rpx;
    
    .result-bar, .score-bar {
      height: 16rpx;
      background: #f0f0f0;
      border-radius: 8rpx;
      overflow: hidden;
      margin: 8rpx 0;
      
      .result-fill, .score-fill {
        height: 100%;
        border-radius: 8rpx;
        transition: width 0.5s ease;
        
        &.completed {
          background: #52c41a;
        }
        
        &.timeout {
          background: #faad14;
        }
        
        &.quit {
          background: #ff4d4f;
        }
      }
      
      .score-fill {
        background: linear-gradient(90deg, #fd79a8 0%, #fdcb6e 100%);
      }
    }
    
    .result-label, .score-count {
      font-size: 24rpx;
      color: #666;
    }
    
    .score-range {
      font-size: 26rpx;
      font-weight: bold;
      color: #333;
    }
  }
}

.popular-emoji-list {
  .popular-emoji-item {
    display: flex;
    align-items: center;
    padding: 16rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .emoji-rank {
      width: 60rpx;
      font-size: 28rpx;
      font-weight: bold;
      color: #fd79a8;
    }
    
    .emoji-char {
      font-size: 40rpx;
      margin-right: 20rpx;
    }
    
    .emoji-stats {
      flex: 1;
      
      .emoji-count {
        display: block;
        font-size: 28rpx;
        color: #333;
        font-weight: bold;
      }
      
      .emoji-users {
        font-size: 24rpx;
        color: #666;
      }
    }
    
    .emoji-percentage {
      font-size: 24rpx;
      color: #fd79a8;
      font-weight: bold;
    }
  }
}

.bottom-actions {
  display: flex;
  gap: 20rpx;
  padding: 20rpx 0;
  
  .action-btn {
    flex: 1;
    padding: 24rpx;
    background: rgba(255, 255, 255, 0.9);
    color: #333;
    border: 2rpx solid #ddd;
    border-radius: 12rpx;
    font-size: 28rpx;
    font-weight: bold;
    
    &:active {
      opacity: 0.8;
    }
  }
}
</style>